<template>
  <div>
    <Navbar
      :appTitle="appTitle"
      :rightShow="true"
      rname="scan"
      @ClickRight="ClickRight"
      @changeScan="navbarScan"
    />
    <div
      class="form-content wrap-apply"
      style="margin-right: 30px;"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <van-cell-group>
        <van-cell center>
          <template #title>
            <p class=" ">
              <span
                style="font-size: 0.38rem;
                       font-family: PingFang SC;
                       font-weight: 500;
                       color:#191f25;
                       margin-bottom: 0.16rem;"
                >{{ detailInfo.pickingCode || "-" }}</span
              >
            </p>
            <p
              class=""
              style="justify-content: space-between;
                    margin-bottom: 0.23rem;
                    color:#191f25"
            >
              <span></span>业务类型 : {{ detailInfo.typeText || "-" }}
            </p>
            <p
              class=""
              style="justify-content: space-between;
                     margin-bottom: 0.23rem;
                     color:#191f25"
            >
              <span></span>拣货员 : {{ detailInfo.picker || "-" }}
            </p>
            <p
              class=""
              style="justify-content: space-between;
                     margin-bottom: 0.23rem;
                     color:#191f25"
              v-if="detailInfo.type !== 'OTHER'"
            >
              <span></span>客户 : {{ detailInfo.customerName || "-" }}
            </p>
          </template>
          <!-- 使用默认插槽自定义内容 -->
          <template #default>
            <p class="" style="color:#fe9400;font-size:0.33rem">
              <span></span>待核验出库:
              {{ detailInfo.unPickedDetailsList.length }}
            </p>
            <p
              class=""
              style="color:#4bd863;font-size:0.33rem"
              @click="GoReceiptedGoods(detailInfo)"
            >
              <span></span>已核验出库:
              {{ detailInfo.pickedDetailsList.length }}
            </p>
          </template>
        </van-cell>

        <div class="bottomLine" style="height:8px"></div>
        <van-cell style="padding-top:0;padding-bottom:0"></van-cell>
        <div class="bottomLine" style="height:3px"></div>

        <div
          class="tabs-contain"
          v-if="
            detailInfo.unPickedDetailsList &&
              detailInfo.unPickedDetailsList.length != 0
          "
        >
          <van-tabs
            v-model="active"
            color="#1989fa"
            title-active-color="black"
            swipe-threshold="3"
            line-width="2.4rem"
            @change="changeTab"
          >
            <van-tab
              v-for="(item, index) in detailInfo.unPickedDetailsList"
              :title="item.goodsName"
              :name="item.goodsName"
              title-class="tab-wrap-ano"
            >
              <div
                class="wrap"
                style="cursor: pointer;"
                v-for="(p, index) in detailInfo.unPickedDetailsList"
              >
                <div style="padding: 11px;" v-if="active === p.goodsName">
                  <div class="top">
                    <van-checkbox
                      v-model="p.checked"
                      :indeterminate="p.indeterminate"
                      @change="changeP($event, index, p)"
                    ></van-checkbox>

                    <div class="title title-m">
                      {{ p.goodsCode || "-" }} | {{ p.goodsName || "-" }}|
                      {{ p.goodsSpec || "-" }}
                    </div>
                  </div>
                  <div class="center">
                    <div>
                      <p>
                        <span class="key">包装规格：</span>
                        <span class="value">{{ p.packageSpec || "-" }}</span>
                      </p>
                      <p>
                        <span class="key">产地：</span>
                        <span class="value">{{ p.address || "-" }}</span>
                      </p>
                      <p>
                        <span class="key">待核验/ 拣货数量 ：</span>
                        <span class="value"
                          >{{ p.unVerificationNum || "-" }}/{{
                            p.pickingQuantity
                          }}</span
                        >
                      </p>
                    </div>
                  </div>
                  <div class="label" style="padding:0 0.42667rem;">
                    <span>{{ p.produceDate || "-" }}</span>
                    <span>{{ p.batchCode || "-" }}</span>
                    <span>{{ p.unitIdText || "-" }}</span>
                  </div>
                </div>
              </div>
            </van-tab>
          </van-tabs>
          <div
            class="all-down-btn"
            v-show="detailInfo.unPickedDetailsList.length > 3"
          >
            <p @click="openDropDownModel">
              <span>全部</span>
              <span>
                <van-icon name="arrow-down" color="#1989fa" size="16" />
              </span>
            </p>
          </div>
          <div class="all-down-model" v-show="allDownShow">
            <div class="tags-contain">
              <span
                class="goodsNameTag"
                v-for="(item, index) in detailInfo.unPickedDetailsList"
                @click="clickGoodsNames(item)"
                :style="{
                  color: item.goodsName == active ? '#1890ff' : '#333333',
                }"
              >
                {{ item.goodsName }}
              </span>
            </div>
            <div class="ctrBtn-contian">
              <span @click="closeDropDownModel">收起</span>
              <span>
                <van-icon name="arrow-up" color="#1989fa" size="16" />
              </span>
            </div>
          </div>
        </div>
      </van-cell-group>
      <div
        v-for="(p, index) in detailInfo.unPickedDetailsList"
        v-show="active === p.goodsName"
      >
        <van-cell-group
          :key="i + '_' + p.serialId"
          style="margin-top: 5px;"
          v-for="(item, i) in p.itemList"
        >
          <div class="wrap" style="padding: 11px;">
            <div class="top">
              <van-checkbox
                v-model="item.checked"
                @change="changeItem($event, index, item)"
              ></van-checkbox>

              <div class="title title-m ">拣货({{ i + 1 }})</div>
            </div>
            <div class="center">
              <div>
                <p>
                  <span class="key">拣货库位：</span>
                  <span class="value"
                    >{{ item.latticeCode || "-" }}|{{
                      item.latticeName || "-"
                    }}</span
                  >
                </p>
                <p>
                  <span class="key">拣货批号：</span>
                  <span class="value">{{ item.batchCode || "-" }}</span>
                </p>
                <p>
                  <span class="key">拣货数量：</span>
                  <span class="value">{{ item.pickingQuantity || "-" }}</span>
                </p>
              </div>
            </div>
          </div>

          <div class="bottomLine"></div>
          <van-cell>
            <template #title>
              <p class="label  required FormTit"><span></span>核验数量</p>
            </template>
            <template #default>
              <div class="">
                <van-field
                  input-align="right"
                  v-model="item.num"
                  placeholder="请输入"
                  type="number"
                  :formatter="(e) => newClearNoNum(e, item.unVerificationNum)"
                />
              </div>
            </template>
          </van-cell>
          <div class="bottomLine"></div>

          <div class="bottomLine"></div>
        </van-cell-group>
      </div>
      <!-- <div class="addGoodScontain">
        <div class="addgoods" @click="showLatticeNotification">
          <van-icon name="plus" size="16px" color="#1890ff" style="top: 2px" />
          <a>库位</a>
        </div>
        <div class="addgoods">
          <scanInputGoods ref="scanGoodsInput" @changeScan="changeScan" />
        </div>
      </div> -->

      <div class="search-bottoms">
        <van-button
          :loading="subLoading"
          loading-text="提交中..."
          class="btnconfirm"
          @click="btnConfirm"
          >提交
        </van-button>
      </div>
    </div>
    <!--选择领出人 -->
    <contact-pickers
      :key="userType"
      :visible="showContactPickers"
      :max="5"
      @closePicker="onCloseContactPickers"
      @confirm="confirmChooseUsers"
    ></contact-pickers>

    <!--选择出库日期 -->
    <van-popup v-model="timePickShow" position="bottom">
      <van-datetime-picker
        @confirm="confirmPick"
        v-model="happenTime"
        @cancel="cancelPick"
        type="date"
        title="生产日期"
        :formatter="formatter"
      />
    </van-popup>
    <!--选择物品 -->
    <goods-pickers
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      :columns="goodsColumns"
      :selectedGoods="entryDetails"
      @getCheckedGoods="getCheckedGoods"
    ></goods-pickers>

    <!--销售订单 -->
    <binLocation-pickers-ak
      v-if="isShowLatticeNotification"
      :selectedGoods="entryDetails"
      @getCheckedValue="getCheckedValue"
      :columns="latticeNotificationgColumns"
      :listUrl="latticeNotificationUrl"
    ></binLocation-pickers-ak>
  </div>
</template>
<script>
import { clearNoNum } from "@/utils/util";
import { getAction } from "@/api/manage";
import moment from "moment";
import Navbar from "../../../components/navBar/navBar_right_outTask";
import {
  wmsPickingTaskQueryById,
  wmsPickingTaskVerification,
} from "@/api/mobile";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import ContactPickers from "@/components/choiceuse/ContactPickers";
import GoodsPickers from "@/components/choiceuse/GoodsPickers";
import saleOrderPickers from "@/components/choiceuse/saleOrderPickers";
import store from "@/store";
import scanInputGoods from "@/components/scanCode/scanInputGoods";
import produceOrderPickers from "@/components/choiceuse/produceOrderPickers";
import { APILX } from "@/api/requestLx";
import { workOrderList } from "@/api/productionApply";
import { getDictItemsByTypes } from "@/api/inventoryOrder";
import BinLocationPickersAk from "@/components/choiceuse/BinLocationPickersAk";
import { getWarehouseLatticeDetail } from "../../../api/inventoryOrder";

export default {
  name: "inventoryOrderForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    ContactPickers,
    GoodsPickers,
    scanInputGoods,
    saleOrderPickers,
    produceOrderPickers,
    BinLocationPickersAk,
  },
  data() {
    return {
      showContactPickers: false,
      userType: "picker", // sendPersion createBy picker
      tabsConfig: {
        all: false,
        showIndex: 0,
      },
      active: "",
      detailInfo: {},
      activeIndex: 0,
      examKey: 1,
      //辅助单位
      buildForm: {
        entryCode: "",
        types: "SALE",
        produceOrderId: "",
        produceOrderName: "",
        saleOrderId: "",
        saleOrderName: "",
        receiverPersion: "",
        receiverPersionName: "",
        outWarehouseTime: "",
        extDataJson: {},
      },

      recentGoodsIndex: 0,
      entryDetails: [],
      happenTime: new Date(),
      appTitle: "核验出库",
      isEdit: false,
      allDownShow: false,
      subLoading: false,
      parentId: "",
      showExam: true,
      warehousingTypes: [],
      selectShow: false,
      timePickShow: false,
      formTypeExtendedFields: [],
      goodsTypeExtendedFields: [],
      showGoodsPicker: false,
      isShowLatticeNotification: false,
      listlatticeNotificationUrlUrl:
        "/wmslattice/getDistributeLatticeNotification",
      latticeNotificationUrl: "",
      latticeNotificationgColumns: {
        titleKey: ["latticeCode", "latticeName"], //标题
        content: [
          //内容
          {
            name: "库位物品",
            key: ["goodsNameTxt"],
          },
          {
            name: "物品数量",
            key: ["goodsNumTxt"],
          },
          {
            name: "物品总数量",
            key: ["totalNum"],
          },
        ],
        labelKey: [], //标签
        operationText: "",
      },
      listUrl: "/wmslattice/getDistributeLatticeNotification",
      goodsColumns: {
        titleKey: ["goodsCode", "goodsName", "spec"], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "基本单位",
            key: ["unitName"],
          },
        ],
        // labelKey: ["updateTime", "serialSpecifications"], //标签
        operationText: "",
      },

      showSaleOrderPickers: false,
      selectedSaleOrder: [],

      showProduceOrderPickers: false,
      selectedProduceOrder: [],
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showPeopleSlect) {
      this.$refs.examine.closePicker();
      next(false);
    } else if (
      this.showGoodsPicker ||
      this.showProduceOrderPickers ||
      this.showSaleOrderPickers
    ) {
      this.showGoodsPicker = false;
      this.showProduceOrderPickers = false;
      this.showSaleOrderPickers = false;
      this.appTitle = this.isEdit ? "核验出库" : "新建出库任务";
      next(false);
    } else {
      next();
    }
  },
  async created() {
    let _this = this;
    getDictItemsByTypes({ type: 4 }).then((res) => {
      if (res.code == 200 && res.result) {
        _this.warehousingTypes = res.result;
        console.log("类型", _this.warehousingTypes);
      }
    });
    // 扫工单码进入
    if (
      this.$route.query.formPage == "scanCode" &&
      this.$route.query.code.EntityType == "workOrder"
    ) {
      let itemRes = await workOrderList({ id: this.$route.query.code.id });
      this.getCheckedProduceOrder(itemRes.result.records);
    }
    // 扫物品码进入
    if (
      this.$route.query.formPage == "scanCode" &&
      this.$route.query.code.EntityType == "goods"
    ) {
      this.changeScan(this.$route.query, "scan");
    }

    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    if (this.$route.query.id) {
      this.isEdit = true;
      this.parentId = this.$route.query.id;
    } else {
      this.isEdit = false;
      this.parentId = "";
    }
    this.buildForm.outWarehouseTime = moment(this.happenTime).format(
      "YYYY-MM-DD HH:mm"
    );
    let currentLoginUser = JSON.parse(
      localStorage.getItem("pro__Login_Userinfo")
    ).value;
    console.log("currentLoginUser", currentLoginUser);
    this.buildForm.receiverPersion = currentLoginUser.id;
    this.buildForm.receiverPersionName = currentLoginUser.realname;
    if (this.parentId) {
      this.appTitle = "核验出库";
    }
    this.initData();
  },
  methods: {
    // tag 弹出层相关功能
    openDropDownModel() {
      this.allDownShow = true;
    },
    closeDropDownModel() {
      this.allDownShow = false;
    },
    clickGoodsNames(item) {
      this.active = item.goodsName;
      console.log(item, item.goodsName, "active");
      this.allDownShow = false;
    },
    changeItem(status, index, itm) {
      let item = this.detailInfo.unPickedDetailsList[index];
      let list = item.itemList;
      let checkedCount = list.filter((t) => t.checked).length;
      // console.log(checkedCount, list.length, list.length === checkedCount);
      // item.checked = list.length === checkedCount;
      item.indeterminate = checkedCount > 0 && checkedCount < list.length;
      let checkLen = item.itemList.filter((im) => im.checked).length;
      if (item.itemList.length === checkLen) {
        this.$set(item, "checked", true);
      } else {
        this.$set(item, "checked", false);
      }
      this.$forceUpdate();
    },
    changeP(status, index, p) {
      if (status) {
        this.detailInfo.unPickedDetailsList[
          index
        ].itemList = this.detailInfo.unPickedDetailsList[index].itemList.map(
          (item) => {
            return { ...item, checked: true };
          }
        );
      } else {
        this.detailInfo.unPickedDetailsList[
          index
        ].itemList = this.detailInfo.unPickedDetailsList[index].itemList.map(
          (item) => {
            return { ...item, checked: false };
          }
        );
      }
      this.$forceUpdate();
    },
    // 确认选中库位
    async getCheckedValue(list) {
      this.showGoodsPicker = false;

      this.entryDetails = list.map((son) => {
        let recIndex = this.entryDetails.findIndex(
          (ele) => ele.serialId == son.id
        );

        if (recIndex != -1) {
          let recObj = this.entryDetails[recIndex];
          return recObj;
        } else {
          let { goodsBatchId, latticeId, pickingQuantity, taskDetailId } = son;

          return {
            goodsBatchId: goodsBatchId,
            latticeId: latticeId,
            pickingQuantity: pickingQuantity,
            taskDetailId: this.parentId,
          };
        }
      });
    },
    // 人员选择 清空
    onClearChooseUsers(userType) {
      this.userType = userType;
      let userNamesKey = this.userType + "Names";

      this.buildForm[userNamesKey] = ""; // 人员name字符串
      this.buildForm[this.userType] = ""; //人员id
    },
    // 人员选择 确认选择回调
    confirmChooseUsers(val, selectedList, judge) {
      if (judge) {
        this.showContactPickers = false;
        return;
      }
      let userNamesKey = this.userType + "Names";
      let arr = [];

      if (selectedList) {
        selectedList.forEach((item) => {
          arr.push(item.realname);
        });
      }

      this.buildForm[userNamesKey] = arr.join(","); // 人员name字符串
      this.buildForm[this.userType] = val ? val : ""; //人员id

      this.showContactPickers = false;
    },
    // 人员选择 关闭
    onCloseContactPickers(userType) {
      this.userType = userType;
      this.showContactPickers = false;
    },
    // 人员选择 打开
    onShowContactPickers(userType) {
      this.userType = userType;
      this.showContactPickers = true;
    },
    //已拣货任务跳转
    GoReceiptedGoods(e) {
      this.$router.push({
        path: "/pickingTasksAlready",
        query: {
          id: this.$route.query.id,
        },
      });
    },
    // 库位选择
    showLatticeNotification(index) {
      this.isShowLatticeNotification = true;
      this.recentGoodsIndex = index;
    },
    // 物品明细-》删除
    deleteGoods(i) {
      this.entryDetails.splice(i, 1);
    },
    //出库类型选择
    selectReport(itemReport, key) {
      if (itemReport) {
        this.buildForm[key] = itemReport.value;
      } else {
        this.buildForm[key] = "";
      }
    },
    // 打开选择时间
    openTimePicker(index, value) {
      this.timePickShow = true;
      this.recentGoodsIndex = index;
      if (value) {
        this.happenTime = value;
      } else {
        this.happenTime = "";
      }
    },
    // 提交 - 表单验证
    btnConfirm() {
      try {
        // 出库物品明细 为空 选项名称、数量 表单验证
        this.detailInfo.unPickedDetailsList.forEach((element, index) => {
          element.itemList.forEach((e, i) => {
            if (e.checked) {
              console.log(e);
              if (!e.num || e.num <= 0) {
                throw new Error("请填写正确的数量");
              }
            }
          });
        });
      } catch (error) {
        this.$toast(error.message);
        return false;
      }

      this.handleSubmit();
    },
    handleSubmit() {
      let itemList = [];
      if (
        this.detailInfo.unPickedDetailsList &&
        this.detailInfo.unPickedDetailsList.length > 0
      ) {
        this.detailInfo.unPickedDetailsList.forEach((element, index) => {
          element.itemList.forEach((e, i) => {
            if (e.checked)
              itemList.push({ detailsId: e.detailsId, num: e.num });
          });
        });
      }
      if (itemList.length == 0) {
        this.$toast("请选择库位并输入正确的核验数量再提交");
        return false;
      }
      let params = {
        taskId: this.$route.query.id,
        itemList: itemList,
      };

      let commitApi = "";
      let successMeg = "";
      if (this.parentId) {
        params.id = this.parentId;
        commitApi = wmsPickingTaskVerification;
        successMeg = "核验出库创建成功！";
      } else {
        commitApi = wmsPickingTaskVerification;
        successMeg = "出库单创建成功！";
      }
      this.subLoading = true;
      commitApi(params)
        .then((res) => {
          if (res.success) {
            this.$toast(successMeg);
            this.$router.go(-1);
          } else {
            this.$toast(res.message);
          }
        })
        .finally(() => {
          this.subLoading = false;
        });
    },
    pickedClick(item, index) {
      this.tabsConfig.showIndex = index;
      this.latticeNotificationUrl =
        this.listlatticeNotificationUrlUrl + `?goodsId=${item.goodsId}`;
    },
    changeTab(e) {
      this.tabsConfig.showIndex = e;
      this.active = e;
      console.log(e, this.active, this.tabsConfig.showIndex);
      this.$forceUpdate();
    },
    // 初始化页面数据
    initData() {
      // 获取出库类型
      // outboundOrderTypeList().then((res) => {
      //   if (res.code == 200 && res.result) {
      //     this.warehousingTypes = res.result;
      //   }
      // });
      let id = this.$route.query.id;
      wmsPickingTaskQueryById({ id: id }).then((res) => {
        if (res.code == 200 && res.result) {
          console.log(123);
          this.detailInfo = res.result;
          // this.entryDetails = res.result;
          this.detailInfo.unPickedDetailsList =
            this.detailInfo.unPickedDetailsList || [];
          // this.detailInfo.itemList = this.detailInfo.itemList || [];
          console.log("detailInfo", this.detailInfo);
        } else {
          this.detailInfo.unPickedDetailsList = [];
          this.entryDetails = res.result;

          console.log("detailInfo", this.detailInfo, this.entryDetails);

          // this.$toast(res.message);
        }
        this.detailInfo.unPickedDetailsList.forEach((item) => {
          item.itemList.forEach((ele) => {
            console.log("ele", ele);
            this.$set(ele, "num", ele.unVerificationNum);
          });
        });

        this.active = this.detailInfo.unPickedDetailsList[0].goodsName;
        this.tabsConfig.showIndex = this.detailInfo.unPickedDetailsList[0].goodsName;
      });
    },
    newClearNoNum(value, maxValue) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = "0";
      }
      //输入长度控制
      if (value > 99999999999999.9999) {
        value = "";
        this.$toast("最多可输入14个字符，小数点后4位");
      }

      if (value > maxValue) {
        value = maxValue;
        this.$toast("不能输入大于" + `${maxValue}` + "的数量");
      }

      return value;
    },
    // 确定选择时间
    confirmPick(date) {
      this.buildForm.outWarehouseTime = moment(date).format("YYYY-MM-DD HH:mm");
      this.entryDetails[this.recentGoodsIndex].produceDate = moment(
        date
      ).format("YYYY-MM-DD");

      this.timePickShow = false;
    },
    // 取消选择时间
    cancelPick() {
      this.timePickShow = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }
      return val;
    },
    // 出库物品明细-》添加
    addInventoryGoods() {
      this.appTitle = "选择物品";
      this.showGoodsPicker = true;
    },
    // 出库物品明细-》物品弹出层
    // projectVisible() {
    //   this.appTitle = "出库物品选择";
    //   this.showGoodsPicker = true;
    // },
    // 确认选中物品
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = this.isEdit ? "核验出库" : "新建出库任务";

      this.entryDetails = list.map((son) => {
        let recIndex = this.entryDetails.findIndex(
          (ele) => ele.serialId == son.id
        );

        let extData = {};
        if (son.extDataJson) {
          extData = son.extDataJson;
        }

        if (recIndex != -1) {
          let recObj = this.entryDetails[recIndex];
          return recObj;
        } else {
          return {
            serialId: son.id,
            serialLongName: son.serialNumber + "|" + son.serialName,
            serialName: son.serialName || "-",
            serialNumber: son.serialNumber || "-",
            serialSpecifications: son.serialSpecifications || "-",
            serialUnit: son.unitName || "-",
            inWarehouseNum: null,
            ...extData,
          };
        }
      });
    },
    // 扫码获取物品
    changeScan(v, opratorType) {
      if (opratorType == "scan") {
        if (v.code.EntityType !== "goods") {
          this.$toast("请扫正确二维码");
          return;
        }

        getAction("/basicserial/basicSerialInfo/queryById", {
          id: v.code.id,
        }).then((res) => {
          if (res.code == 200 && res.result) {
            let ids = this.entryDetails.map((item) => item.serialId);
            if (ids.includes(res.result.id)) {
              this.$toast("该物品已存在");
              return;
            } else {
              let {
                id,
                serialName,
                serialNumber,
                serialSpecifications,
                unitName,
              } = res.result;
              let newGoods = {
                serialId: id,
                serialLongName: serialName + "|" + serialNumber,
                serialName: serialName || "-",
                serialNumber: serialNumber || "-",
                serialSpecifications: serialSpecifications || "-",
                serialUnit: unitName || "-",
                inWarehouseNum: null,
              };
              if (this.entryDetails && this.entryDetails.length == 1) {
                if (!this.entryDetails[0].serialId) {
                  this.entryDetails = [];
                  this.entryDetails.push(newGoods);
                } else {
                  this.entryDetails.push(newGoods);
                }
              } else {
                this.entryDetails.push(newGoods);
              }
              this.$forceUpdate();
            }
            // for (const goods of this.entryDetails) {
            // if (goods.serialId == res.result.id) {
            //   this.$toast("该物品已存在");
            //   break;
            // } else {
            // let {
            //   id,
            //   serialName,
            //   serialNumber,
            //   serialSpecifications,
            //   serialUnit,
            // } = res.result;
            // let newGoods = {
            //   serialId: id,
            //   serialLongName: serialName + "|" + serialNumber,
            //   serialName: serialName || "-",
            //   serialNumber: serialNumber || "-",
            //   serialSpecifications: serialSpecifications || "-",
            //   serialUnit: serialUnit || "-",
            //   inWarehouseNum: null,
            // };
            // this.entryDetails.push(newGoods);
            // this.$forceUpdate();
            // }
            // }
          }
        });
      }
    },

    // 销售订单-》添加
    addSaleOrder() {
      this.appTitle = "销售订单选择";
      this.showSaleOrderPickers = true;
    },
    // 销售订单-》删除
    deleteSaleOrder() {
      this.buildForm.saleOrderId = "";
      this.buildForm.saleOrderName = "";
      this.selectedSaleOrder = [];
    },
    // 确认选中销售订单
    async getCheckedSaleOrder(list) {
      if (!list[0].id) {
        return;
      } else {
        this.buildForm.saleOrderId = list[0].id;
        this.buildForm.saleOrderName = list[0].orderCode;
        this.selectedSaleOrder = list;
      }
      this.showSaleOrderPickers = false;
      this.appTitle = this.$route.meta.title;

      APILX.saleOrderDetail(list[0].id).then((res) => {
        if (res.code == 200) {
          if (res.result.records && res.result.records.length != 0) {
            this.entryDetails = res.result.records.map((ele) => {
              return {
                serialId: ele.bsiId,
                serialLongName: ele.serialCode + "|" + ele.serialName,
                serialName: ele.serialName || "-",
                serialNumber: ele.serialNumber || "-",
                serialSpecifications: ele.serialSpecifications || "-",
                serialUnit: ele.unitName || "-",
                inWarehouseNum: ele.serialNumber || null,
              };
            });
          }
        } else {
          this.$toast(res.message);
        }
      });
    },

    // 生产工单-》添加
    addProduceOrder() {
      this.appTitle = "生产工单选择";
      this.showProduceOrderPickers = true;
    },
    // 生产工单-》删除
    deleteProduceOrder() {
      this.buildForm.produceOrderId = "";
      this.buildForm.produceOrderName = "";
      this.selectedProduceOrder = [];
    },
    // 确认选中生产工单
    async getCheckedProduceOrder(list) {
      if (!list[0].id) {
        return;
      } else {
        this.buildForm.produceOrderId = list[0].id;
        this.buildForm.produceOrderName = list[0].orderCode;
        this.selectedProduceOrder = list;
      }
      this.showProduceOrderPickers = false;
      this.appTitle = this.$route.meta.title;

      APILX.produceOrderInfoQueryById({ id: list[0].id }).then((res) => {
        if (res.code == 200) {
          this.entryDetails = [
            ...res.result.records.map((item) => {
              let {
                serialId,
                serialName,
                serialNumber,
                serialSpecifications,
                unitName,
                planProduceNum,
                maxQualifiedNum,
              } = item;
              return {
                serialId: serialId,
                serialLongName: serialNumber + "|" + serialName,
                serialName: serialName || "-",
                serialNumber: serialNumber || "-",
                serialSpecifications: serialSpecifications || "-",
                serialUnit: unitName || "-",
                inWarehouseNum: maxQualifiedNum,
              };
            }),
          ];
        } else {
          this.$toast(res.message);
        }
      });
    },

    // 出库单 物品明细 数量处理
    needOutNumChange(e) {
      let value = clearNoNum(e);
      return value;
    },

    ClickRight() {
      this.showGoodsPicker = false;
      // this.$router.push({
      //   path: "/application",
      // });
    },
    navbarScan(v, type) {
      console.log(v, type, "扫描结果");
      if (v.code.EntityType !== "goods") {
        this.$toast("请扫正确二维码");
      }

      this.detailInfo.unPickedDetailsList.forEach((item) => {
        console.log("0000");
        item.itemList.forEach((itm) => {
          if (!item.batchCode && item.goodsId === v.code.id) {
            console.log("11111", item);
            this.active = item.goodsName;
            this.$set(item, "checked", true);
            this.$set(itm, "checked", true);
            this.$toast("扫描成功");
          } else if (
            itm.batchCode === v.code.batchCode &&
            item.goodsId === v.code.id
          ) {
            console.log("2222", item);
            this.active = item.goodsName;
            this.$set(itm, "checked", true);
            this.$toast("扫描成功");
          }
        });
      });

      this.$forceUpdate();
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";

.wrap-apply {
  /deep/ .van-field__control--right {
    text-align: right !important;
  }
}

.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  overflow: scroll;
  padding: 20px 0;

  .label {
    padding: 0.2rem 0 0.32rem;
  }

  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }

  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;

    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
  }
}

.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}

.otherText {
  font-size: 32px;
  font-weight: bold;
  color: #191f25;
  padding-left: 20px !important;
}

.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;

  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }

  /deep/ .van-field__control {
    max-width: 700px;
  }
}

/deep/ .van-nav-bar {
  z-index: 99;
}

/deep/ .van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}

/deep/ .van-tree-select__item--active {
  color: #1890ff;
  border-bottom: 2px solid #1890ff;
}

.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;

  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}

.required span::after {
  left: -20px;
  top: 3px;
}

.filedClear {
  width: 28px;
  height: 28px;
}

.wrap {
  background: #fff;
  width: 100vw;

  .top {
    display: flex;
    justify-content: flex-start;

    .icon {
      width: 6px;
      height: 36px;
      background: #1890ff;
      margin-top: 6px;
      margin-right: 20px;
    }

    .title {
      width: 620px;
      margin-right: 20px;
      font-size: 32px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #191f25;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .title-m {
      margin-left: 0.3rem;
    }

    .spot img {
      width: 40px;
      height: 40px;
    }
  }

  .center {
    p {
      margin: 16px 25px;
      font-size: 28px;
      display: flex;
      position: relative;

      .key {
        color: #888888;
      }

      .value {
        color: #191f25;
        width: 380px;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .arrow {
        color: #1890ff;
        // float: right;
        // margin-right: -0.05rem;
        // display: block;
        position: absolute;
        right: -10px;
      }
    }

    .showAll {
      background: #f5f8ff;
      width: 100vw;
      margin-left: -0.15rem;
      padding: 0.15rem;
      margin-bottom: 0.15rem;
    }

    .fontAno {
      font-size: 30px;
      padding-left: 20px;
    }
  }

  .label {
    margin-left: -0.03rem;
    margin-top: -0.1rem;

    span {
      height: 0.16rem;
      background: #f0f6fe;
      color: #1890ff;
      margin-right: 0.1rem;
      padding: 0.03rem 0.08rem;
      border-radius: 0.03rem;
      font-size: 28px;
    }
  }

  .foot {
    // height: 0.33rem;
    // line-height: 0.33rem;
    display: flex;
    justify-content: space-between;
    // margin: 0.15rem 0.12rem 0 0.12rem;
    font-size: 0.14rem;

    .pictures {
      width: 0.33rem;
      height: 0.33rem;
      line-height: 0.33rem;
      text-align: center;
      color: #fff;
      background: #1890ff;
      display: block;
      border-radius: 0.06rem;
      font-size: 0.12rem;
      margin-right: 0.1rem;
    }

    .text {
      width: 1rem;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .opera {
      color: #1890ff;
      font-size: 0.14rem;
    }
  }
}

.tabs-box-rel {
  position: relative;
  height: 22.51px;

  .tabs-up {
    position: absolute;
    width: 100%;
    background: #fff;
  }
}

.tabs-box {
  .tabs {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20px;

    .tab {
      width: 25%;
      text-align: center;
      font-size: 0.4rem;
      cursor: pointer;
      padding: 20px 0;
      margin-right: 20px;
    }

    .tabsAll {
      color: #1890ff;
      z-index: 20;
    }

    .active {
      color: #1890ff;
    }
  }

  .arrow-up-tab {
    color: #1890ff;
    text-align: center;
    font-size: 0.4rem;
  }
}

.tabs-contain {
  position: relative;

  /deep/ .van-tabs__nav--line.van-tabs__nav--complete {
    width: calc(100% - 120px);
  }

  /deep/ .van-tabs__wrap--scrollable .van-tab {
    width: 33%;
    min-width: 230px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .all-down-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 120px;
    height: 90px;
    font-size: 28px;
    color: rgb(25, 137, 250);
    line-height: 90px;
    text-align: center;
    background-color: #fff;

    /deep/ .van-icon {
      top: 6px;
    }
  }

  .all-down-model {
    position: absolute;
    top: 0;
    right: 0;
    width: 100vw;
    background-color: #fff;
    z-index: 9;
    border-bottom: 1px solid #f3f3f3;
    padding: 6px;

    .tags-contain {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;

      .goodsNameTag {
        width: 22%;
        margin: 10px 10px;
        padding: 5px 20px;
        background-color: #f3f3f3;
        color: #333333;
        border-radius: 5px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        text-align: center;
        height: 60px;
        line-height: 42px;
      }
    }

    .ctrBtn-contian {
      height: 50px;
      text-align: center;
      color: #1890ff;
      font-size: 24px;
      line-height: 50px;

      /deep/ .van-icon {
        top: 6px;
      }
    }
  }
}
</style>
